package com.ylr.send.framework.service.impl;

import com.ylr.send.framework.manager.SmsManager;
import com.ylr.send.framework.properties.AliSmsProperties;
import com.ylr.send.framework.service.SmsService;
import com.ylr.send.common.dto.SendSmsDto;
import com.ylr.send.common.enums.SmsChannelEnum;
import com.ylr.send.common.enums.SmsEnum;
import com.alibaba.fastjson2.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.ylr.send.framework.entity.SmsTemplateEntity;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-06-14 15:52:38
 * className: AliSmsServiceImpl
 * version: 1.0
 * description:
 */
@Service("aliSmsService")
@AllArgsConstructor
public class AliSmsServiceImpl implements SmsService {

    private static final Logger log = LoggerFactory.getLogger(AliSmsServiceImpl.class);

    private final AliSmsProperties aliSmsProperties;

    @PostConstruct
    public void init() {
        SmsManager.register(SmsChannelEnum.ALI.getValue(), this);
    }

    @Override
    public SendSmsDto sendSms(String mobile, SmsTemplateEntity smsTemplate, Map<String, String> paramMap) {
        log.info("开始阿里云短信发送");

        DefaultProfile profile = DefaultProfile.getProfile(aliSmsProperties.getRegionId(),
                aliSmsProperties.getAccessKeyId(), aliSmsProperties.getAccessKeySecret());
        // 构造阿里云请求客户端对象
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest smsRequest = new SendSmsRequest();
        // 设置接收短信的手机号
        smsRequest.setPhoneNumbers(mobile);
        // 设置阿里云短信服务签名
        smsRequest.setSignName(aliSmsProperties.getSignName());
        // 设置短信模板的名称
        smsRequest.setTemplateCode(smsTemplate.getCode());
        // 设置短信参数
        smsRequest.setTemplateParam(JSON.toJSONString(paramMap));

        SendSmsDto sendSmsDto = new SendSmsDto();
        sendSmsDto.setStatus(SmsEnum.SEND_SUCCESS.getValue());
        try {
            // 向阿里云短信服务发送消息
            SendSmsResponse smsResponse = client.getAcsResponse(smsRequest);
            log.info("阿里云短信服务发送返回结果：{}", JSON.toJSONString(smsResponse));
            if (!"OK".equals(smsResponse.getCode())) {
                log.error("短信发送失败，请务必及时处理");
                sendSmsDto.setStatus(SmsEnum.SEND_FAIL.getValue())
                        .setMsg(smsResponse.getMessage());
            }
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("requestId", smsResponse.getRequestId());
            resultMap.put("bizId", smsResponse.getBizId());
            sendSmsDto.setResultMap(resultMap);
        } catch (ClientException e) {
            log.error("阿里云短信服务api调用异常。message={}", e.getMessage(), e);
            sendSmsDto.setStatus(SmsEnum.SEND_FAIL.getValue())
                    .setMsg("阿里云短信服务api调用异常");
        } catch (Exception e) {
            log.error("阿里云短信发送异常。message={}", e.getMessage(), e);
            sendSmsDto.setStatus(SmsEnum.SEND_FAIL.getValue())
                    .setMsg("阿里云短信发送异常");
        }
        log.info("阿里云短信发送结束");
        return sendSmsDto;
    }

    @Override
    public SendSmsDto batchSendSms(List<String> mobileList, SmsTemplateEntity smsTemplate, Map<String, String> paramMap) {
        return null;
    }

    @Override
    public Map<String, String> addChannelParam(Map<String, String> paramMap) {
        // 这里添加短信渠道特有的参数
        return paramMap;
    }

    @Override
    public Map<String, String> getChannelParam() {
        return Collections.emptyMap();
    }

}
